package com.henry.album.util;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import com.alibaba.fastjson.JSON;

public class MyHttpHelper {

	public static void main(String[] args) {

		// get
		/*
		 * MyHttpHelper.get("http://192.168.0.198:13301/hzpjg/cpxx.json", new
		 * Callback() {
		 * 
		 * @Override public void onSuccess(String res) {
		 * System.out.println(res);
		 * 
		 * }
		 * 
		 * @Override public void onFinally(String res) {
		 * 
		 * System.out.println(res); }
		 * 
		 * @Override public void onFail(String res) { System.out.println(res);
		 * 
		 * } });
		 */

		MyHttpHelper.getImage("http://192.168.0.198:13301/down_/123.jpeg", res -> {

			System.out.println("请求成功");

			try {
				// 创建一个文件对象用来保存图片，默认保存当前工程根目录，起名叫Copy.jpg
				File imageFile = new File("D:/Copy2.jpg");
				// 创建输出流
				FileOutputStream outStream = new FileOutputStream(imageFile);
				// 写入数据
				outStream.write(res.getData());
				outStream.flush();
				CloseIO(outStream);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		});
	}

	interface Callback {

		public abstract void onSuccess(String res);

		default void onFail(String msg) {

			System.out.println(msg);
		}

		default void onFinally(String msg) {
			System.out.println(msg);
		}
	}

	interface ImageCallback {

		public void onSuccess(ImageResponse response);

		default void onFail(String msg) {

			System.out.println(msg);
		}

		default void onFinally(String msg) {
			System.out.println(msg);
		}
	}



	/**
	 * 默认get请求
	 * 
	 * @param urlStr
	 */
	public static void getImage(String urlStr, ImageCallback callback) {

		ByteArrayOutputStream byteoutStream = null;
		InputStream is = null;
		HttpURLConnection connection = null;
		try {
			URL url = new URL(urlStr);
			// 打开连接
			connection = (HttpURLConnection) url.openConnection();
			// 设置请求方式为"GET"
			connection.setRequestMethod("GET");
			// 设置是否向HttpURLConnection输出
			connection.setDoOutput(false);
			// 设置是否从HttpUrlConnection读入
			connection.setDoInput(true);
			// 超时响应时间为20秒
			connection.setConnectTimeout(20 * 1000);
			// 打开链接
			connection.connect();

			int code = connection.getResponseCode();

			if (code == 200) {
				
				
				
				// 获取文件名
				String fileName = "myfile";
				String contentDisposition = connection.getHeaderField("Content-Disposition");
				if (contentDisposition != null) {
				    int index = contentDisposition.indexOf("filename=");
				    if (index > 0) {
				        fileName = contentDisposition.substring(index + 9);
				        if (fileName.startsWith("\"")) {
				            int endIndex = fileName.lastIndexOf("\"");
				            if (endIndex > 0) {
				                fileName = fileName.substring(1, endIndex);
				            }
				        }
				    }
				}
				

				// 通过输入流获取图片数据
				is = connection.getInputStream();
				// 得到图片的二进制数据，以二进制封装得到数据，具有通用性
								

				byteoutStream = new ByteArrayOutputStream();
				// 创建一个Buffer字符串
				byte[] buffer = new byte[1024 * 2];
				// 每次读取的字符串长度，如果为-1，代表全部读取完毕
				int len;
				long totalLength =0L;
				// 使用一个输入流从buffer里把数据读取出来
				while ((len = is.read(buffer)) != -1) {
					// 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
					byteoutStream.write(buffer, 0, len);
					
					totalLength+=len;
				}

				byte[] data = byteoutStream.toByteArray();

				ImageResponse res = new ImageResponse();
				
				res.setData(data);
				res.setLength(totalLength);
				res.setFileName(fileName);
				
				callback.onSuccess(res);
			} else {

				callback.onFail("请求码异常：" + code);
			}

		} catch (Exception e) {

			e.printStackTrace();
			callback.onFail("请求异常：");

		} finally {
			// 关闭输出流，释放资源
			connection.disconnect();
			CloseIO(is);
			CloseIO(byteoutStream);
			callback.onFinally("请求结束");
		}

	}

	/**
	 * get请求
	 * 
	 * 
	 * @param urlStr
	 * @param callback
	 */
	public static void post(String urlStr, Map<String, Object> params, Callback callback) {

		// NetManager netManager = NetManager.getInstance(null);
		// if (!netManager.hasDefaultNet()) {
		// LogUtils.debug("NetRequestUtils network is null");
		// return;
		// }

		// NetHandle netHandle = netManager.getDefaultNet();
		// netManager.addDefaultNetStatusCallback(callback);

		HttpURLConnection connection = null;
		ByteArrayOutputStream outputStream = null;
		InputStream inputStream = null;

		OutputStream out = null;
		try {

			outputStream = new ByteArrayOutputStream();

			URL url = new URL(urlStr);
			// URLConnection urlConnection = netHandle.openConnection(url,
			// java.net.Proxy.NO_PROXY);
			URLConnection urlConnection = url.openConnection();
			if (urlConnection instanceof HttpURLConnection) {
				connection = (HttpURLConnection) urlConnection;
			}
			// 设置是否使用缓存
			connection.setUseCaches(false);

			connection.setRequestMethod("POST");
			// 设置是否向HttpURLConnection输出
			connection.setDoOutput(true);
			// 设置是否从HttpUrlConnection读入
			connection.setDoInput(true);
			// 设置超时时间
			connection.setConnectTimeout(3000);
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

			String jsonString = JSON.toJSONString(params);

			connection.connect();
			out = connection.getOutputStream();
			out.write(jsonString.getBytes());

			int code = connection.getResponseCode();

			if (code == 200) {// 正常响应

				try {
					inputStream = urlConnection.getInputStream();

					byte[] cache = new byte[2 * 1024];
					int len = inputStream.read(cache);
					while (len != -1) {
						outputStream.write(cache, 0, len);
						len = inputStream.read(cache);
					}
					String result = new String(outputStream.toByteArray());
					callback.onSuccess(result);

				} catch (IOException e) {

					callback.onFail("读流异常");

					e.printStackTrace();
				} finally {

					// 断开连接，释放资源
					connection.disconnect();
				}
			} else {
				callback.onFail("请求异常：" + code);
			}

			// getUITaskDispatcher().syncDispatch(() ->
			// Toast.show("成功发起get网络请求：" +
			// result));
			// HttpResponseCache.getInstalled().flush();

		} catch (IOException e) {
			e.printStackTrace();
			callback.onFail("访问异常");

		} finally {

			CloseIO(out);
			CloseIO(outputStream);
			CloseIO(inputStream);
			callback.onFinally("请求结束");

		}

	}

	/**
	 * get请求
	 * 
	 * 
	 * @param urlStr
	 *            参数要提前拼接好
	 * @param callback
	 */
	public static void get(String urlStr, Callback callback) {

		// NetManager netManager = NetManager.getInstance(null);
		// if (!netManager.hasDefaultNet()) {
		// LogUtils.debug("NetRequestUtils network is null");
		// return;
		// }

		// NetHandle netHandle = netManager.getDefaultNet();
		// netManager.addDefaultNetStatusCallback(callback);

		HttpURLConnection connection = null;
		ByteArrayOutputStream outputStream = null;
		InputStream inputStream = null;
		try {

			outputStream = new ByteArrayOutputStream();

			URL url = new URL(urlStr);
			// URLConnection urlConnection = netHandle.openConnection(url,
			// java.net.Proxy.NO_PROXY);
			URLConnection urlConnection = url.openConnection();
			if (urlConnection instanceof HttpURLConnection) {
				connection = (HttpURLConnection) urlConnection;
			}
			// 设置是否使用缓存
			connection.setUseCaches(false);

			connection.setRequestMethod("GET");
			// 设置是否向HttpURLConnection输出
			connection.setDoOutput(false);
			// 设置是否从HttpUrlConnection读入
			connection.setDoInput(true);
			// 设置超时时间
			connection.setConnectTimeout(3000);
			connection.connect();

			int code = connection.getResponseCode();

			if (code == 200) {// 正常响应

				try {
					inputStream = urlConnection.getInputStream();

					byte[] cache = new byte[2 * 1024];
					int len = inputStream.read(cache);
					while (len != -1) {
						outputStream.write(cache, 0, len);
						len = inputStream.read(cache);
					}
					String result = new String(outputStream.toByteArray());
					callback.onSuccess(result);

				} catch (IOException e) {

					callback.onFail("读流异常");

					e.printStackTrace();
				} finally {

					// 断开连接，释放资源
					connection.disconnect();
				}
			} else {
				callback.onFail("请求异常：" + code);
			}

			// getUITaskDispatcher().syncDispatch(() ->
			// Toast.show("成功发起get网络请求：" +
			// result));
			// HttpResponseCache.getInstalled().flush();

		} catch (IOException e) {
			e.printStackTrace();
			callback.onFail("访问异常");

		} finally {

			CloseIO(outputStream);
			CloseIO(inputStream);
			callback.onFinally("请求结束");

		}

	}

	/**
	 * 关闭流
	 * 
	 * @param io
	 */
	public static void CloseIO(Closeable io) {
		try {
			if (io != null) {

				io.close();
			}
		} catch (Exception e) {

		} finally {
			io = null;
		}

	}

}
